package com.zhiwang.xiaoqu.ui


import androidx.fragment.app.Fragment
import com.hiray.exception.ExpiredException
import com.hiray.exception.XQException
import com.tencent.bugly.crashreport.CrashReport
import com.zhiwang.xiaoqu.App
import com.zhiwang.xiaoqu.BuildConfig
import com.zhiwang.xiaoqu.bus.LogoutEvent
import com.zhiwang.xiaoqu.mvp.model.sharepref.PrefManager
import com.zhiwang.xiaoqu.mvp.view.AuthView
import com.zhiwang.xiaoqu.widget.Toasty
import io.reactivex.disposables.Disposable
import org.greenrobot.eventbus.EventBus
import quickStartActivity

/**
 * A simple [Fragment] subclass.
 */
open class BaseFragment : Fragment(), AuthView {


    fun getAppComponent() = (context!!.applicationContext as App).appComponent


    open override fun onError(t: Throwable) {
        if (t is ExpiredException) {
            EventBus.getDefault().post(LogoutEvent())
            PrefManager.clearToken()
            onAuthExpired()
        } else if (t is XQException) {
            t.message?.apply { Toasty.message(this) }
        } else {
            CrashReport.postCatchedException(t)
        }
    }

    override fun onAuthExpired() {
        quickStartActivity(PhoneLoginActivity::class.java)
    }


    private var disposableCollection: ArrayList<Disposable> = ArrayList()

    fun addToDiposable(disposable: Disposable?) {
        if (disposable != null && disposable.isDisposed.not())
            disposableCollection.add(disposable)
    }

    override fun onDestroy() {
        super.onDestroy()
        for (disposable in disposableCollection) {
            if (disposable.isDisposed.not())
                disposable.dispose()
        }
    }


    fun webViewHeader(): Map<String, String> {
        return mapOf(
            Pair("appdevice", "android")
            , Pair("apptoken", PrefManager.token())
            , Pair("appversion", BuildConfig.VERSION_CODE.toString())
        )
    }
}
